/**
 * 
 */
package com.juliashine.db.zzy;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

/**
 * @author Juliashine@gmail.com 2011-5-16
 *
 */
public class DBCfg {

	static String DEFAULT_XML_PATH = "/db-cfg.xml";
	static Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
	
	Map<String, Param> paramMap = new HashMap<String, Param>();
	Map<String, DBDesc> dsMap = new HashMap<String, DBDesc>();
	
	private String xmlcfgPath = DEFAULT_XML_PATH;
	
	public DBCfg(){
		this(DEFAULT_XML_PATH);
	}
	
	public DBCfg(String xmlpath){
		if(xmlpath != null)
			this.xmlcfgPath = xmlpath;
		init();
	}
	
	void init(){
		System.out.println(xmlcfgPath);
		    
        try {
        	Digester digester = new Digester();
            digester.setValidating(false);
            InputStream is = this.getClass().getResourceAsStream(xmlcfgPath);

//            digester.addObjectCreate("dbcfg", DBCfg.class );            
            digester.push(this);
            
            String xpath_params = "dbcfg/params/param";

            digester.addObjectCreate(xpath_params, Param.class );
            digester.addSetRoot(xpath_params, "addParam" );
            digester.addSetProperties(xpath_params);
            digester.addCallMethod(xpath_params,"setValue",0);
                             
            String xpath_ds = "dbcfg/datasources/datasource";
            digester.addObjectCreate(xpath_ds, DBDesc.class );
            digester.addSetProperties(xpath_ds);
            digester.addSetRoot(xpath_ds,"addDs");       
            digester.addBeanPropertySetter(xpath_ds+"/host");
            digester.addBeanPropertySetter(xpath_ds+"/drivername");
            digester.addBeanPropertySetter(xpath_ds+"/dbname");
            digester.addBeanPropertySetter(xpath_ds+"/username");
            digester.addBeanPropertySetter(xpath_ds+"/password");
            digester.addSetRoot(xpath_ds, "matchParams");
                                         
            DBCfg cfg = (DBCfg)digester.parse(is);
            
			System.out.println(cfg.getDsMap().size());
			if(cfg.getDsMap().size() >0){
				for(String id : cfg.getDsMap().keySet()){
					System.out.println(id);
					DBDesc ds = cfg.getDsMap().get(id);
					System.out.println(ds);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
	
	
	public Map<String, Param> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, Param> paramMap) {
		this.paramMap = paramMap;
	}

	public Map<String, DBDesc> getDsMap() {
		return dsMap;
	}

	public void setDsMap(Map<String, DBDesc> dsMap) {
		this.dsMap = dsMap;
	}

	public void addParam(Param param){
//		System.out.println("addParam " + param.getId() + "\t" + param.getValue());
		paramMap.put(param.getId(), param);
//		System.out.println(paramMap.size());
	}
	
	public void addDs(DBDesc ds) {
		dsMap.put(ds.getId(), ds);
	}
	
	DBDesc getDs(String dsId){
		
		return null;
	}
	
	public void matchParams(DBDesc ds) throws Exception{
//		System.out.println("matchParams " + ds.getId());
		ds.setDbname(replace(ds.getDbname()));
		String host = ds.getHost();
		ds.setHost(replace(host));
		String driverName = ds.getDrivername();
		ds.setDrivername(replace(driverName));
		String userName = ds.getUsername();
		ds.setUsername(replace(userName));
		String pwd = ds.getPassword();
		ds.setPassword(replace(pwd));

	}
	
	private String replace(String param) throws Exception{
		String value = param;
		Matcher matcher = pattern.matcher(param);
		if(matcher.matches()){
			String key = matcher.group(1);
//			System.out.println(key);
			if(paramMap.get(key) == null)
				throw new Exception("param '" + key + "' has not been set !");
			value = paramMap.get(key).getValue();		
		}	
		return value;
	}
	
	public static void main(String[] args){
//		Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
//		String str = "${driver_mysql}";
//		Matcher matcher = pattern.matcher(str);
//		System.out.println((matcher.matches()));
//		String key = matcher.group(1);
//		System.out.println(key);
		DBCfg db = new DBCfg();
	}
}
